package com.hanggold.springboot.lesson4.select;

import com.hanggold.springboot.lesson4.annotation.EnableServer;
import com.hanggold.springboot.lesson4.enumo.ServerType;
import com.hanggold.springboot.lesson4.service.FtpServer;
import com.hanggold.springboot.lesson4.service.HttpServer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

public class ServerImportantSelector implements ImportSelector, DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
        BeanFactoryAware, EnvironmentAware, Ordered {

    private Environment environment;

    private ClassLoader classLoader;

    private BeanFactory beanFactory;

    private ResourceLoader resourceLoader;

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {

        Map<String, Object> map = importingClassMetadata.getAnnotationAttributes(EnableServer.class.getName());

        ServerType serverType = (ServerType) map.get("type");

        String[] importClassNames = new String[0];

        if (serverType == ServerType.FTP){
            importClassNames = new String[]{FtpServer.class.getName()};
        }else{

            importClassNames = new String[]{HttpServer.class.getName()};
        }
        return importClassNames;
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }


    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
            this.classLoader = classLoader;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
